package bank

// 存款通道
var deposits = make(chan int)

// 余额查询通道
var balances = make(chan int)

// 取款通道 - 现在传递的是取款请求结构体
var withdrawals = make(chan withdrawal)

type withdrawal struct {
	amount int
	result chan bool
}

// Deposit 存款函数
func Deposit(amount int) { deposits <- amount }

// Balance 余额查询函数
func Balance() int { return <-balances }

// Withdraw 取款函数
func Withdraw(amount int) bool {
	resultChan := make(chan bool)

	//创建管道保存到全局取款管道中， 等待全局取款管道被处理
	withdrawals <- withdrawal{amount: amount, result: resultChan}
	return <-resultChan
}

func taller() {

	//余额， 只在teller中使用
	var balance int
	for {

		select {
		case amount := <-deposits:
			balance += amount
		case balances <- balance:

		case w := <-withdrawals:
			if w.amount <= balance {
				balance -= w.amount
				w.result <- true
			} else {
				w.result <- false
			}

		}

	}
}

func init() {
	go taller()
}
